package com.zja.service.Impl;

import com.zja.dao.Impl.UserDaoImpl;
import com.zja.dao.UserDao;
import com.zja.model.User;
import com.zja.service.UserService;

import java.sql.Timestamp;


/**
 * @author JA
 * @date: 2025/5/2
 * description:
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDaoImpl();

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        //未加密密码匹配，后期需改为加密对比
        try {
            for(User user :userDao.selectAll()){
                if(user.getUsername().equals(username) && user.getPassword().equals(password)){
                    return user;
                }
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("登录失败",e);
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public boolean register(User user) {
        //校验用户名和邮箱唯一
        try {
            for(User u : userDao.selectAll()){
                if(u.getUsername().equals(user.getUsername()) ||u.getEmail().equals(user.getEmail())){
                    return false;
                }
            }
            Timestamp now = new Timestamp(System.currentTimeMillis());
            user.setCreateTime(now);
            user.setUpdateTime(now);
            if(user.getRole() == null){
                user.setRole("user");
                //默认角色
            }
            return userDao.insert(user);
        } catch (Exception e) {
            throw new RuntimeException("注册失败",e);
        }
    }

    @Override
    public User findById(Long id) {
        return userDao.selectById(id);
    }

    @Override
    public User findByUsername(String username) {
        return userDao.selectByUserName(username);
    }

    @Override
    public User findByEmail(String email) {
        return userDao.selectByEmail(email);
    }
}
